package com.example.oracle.controller;

import com.example.oracle.service.UserService;
import com.example.oracle.domain.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UsersController {

    @Autowired
    private UserService userService;

    @PostMapping("")
    public JData insert(@RequestBody User user){
        if(user.getUsername()==null){
            return new JData("1","username null",0);
        }
        if(user.getPassword()==null){
            return new JData("1","password null",0);
        }
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        userService.insert(user);
        return new JData("0","ok",user);
    }

    @DeleteMapping("/{id}")
    public  JData delete(@PathVariable Long id){
        int result = userService.delete(id);
        return new JData("0","ok",result);
    }

    @PutMapping("")
    public JData update(@RequestBody User user){
        if(user.getPassword()!=null){
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        }
        int result = userService.update(user);
        return new JData("0","ok",result);
    }

    @GetMapping("/{id}")
    public JData getFindById(@PathVariable Long id){
        User result = userService.findById(id);
        return new JData("0","ok",result);
    }

    @GetMapping("/list")
    public JData getList(@RequestParam(value = "username",required = false) String username,
                         @RequestParam(value = "phone",required = false) String phone,
                         @RequestParam(value = "page",required = false) Integer page,
                         @RequestParam(value = "pageSize",required = false) Integer pageSize){
        Map<String,Object> params = new HashMap<String,Object>();
        if(username!=null){
            params.put("username",username);
        }
        if(phone!=null){
            params.put("phone",phone);
        }
        if(page!=null){
            params.put("page",page);
        }
        if(pageSize!=null){
            params.put("pageSize",pageSize);
        }
        List<User> result = userService.getList(params);
        return new JData("0","ok",result);
    }



}
